<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Validator;

use App\Http\Models\ProjectModel;
use App\Http\Models\VipModel;
use App\Http\Models\TemplateModel;
use App\Http\Models\SettingsModel;
use App\Http\Models\ClearModel;
use App\Http\Models\MarketTypeModel;
use App\Http\Models\ActionLogModel;

class ProjectController extends HomeController
{
	// 我的项目
    public function lists(Request $request)
	{
		try{
			$pagesize = $request->input('pagesize', 9);
			$pageno = $request->input('pageno', 1);
	
			$data = ProjectModel::where(["uid" => $this->user->id])->having('status', '>', 0)->orderBy("modify_time", "desc")->orderBy("create_time","desc") -> skip(($pageno-1) * $pagesize)->take($pagesize)->get();

			return response()->json(build_result(["info"=>build_project_info($data), "pagesize" => $pagesize, "pageno" => $pageno]));
		}catch(\Exception $e) {
			return response()->json(build_result('', '10001', $e->getMessage()));	
		}
	}

	// 获取用户项目个数限制
	public function count()
	{
		try
		{
			$count = ProjectModel::count($this->user->id);
			$limit = VipModel::getLevelExtraInfoByKey($this->user->id);
			if(!$limit) return response()->json(build_result('', '31001', ''));
			return response()->json(build_result(["count" => $count, "limit" => $limit]));
		} catch(\Exception $e)
		{
			return response()->json(build_result('', '10001', $e->getMessage()));
		}
	}

	// 删除项目
	public function remove(Request $request)
	{
		try{
			$this->validate($request, [
				'apptoken' => 'required'
			]);
			$apptoken = $request->input('apptoken');

			$ret = ProjectModel::remove($this->user->id, $apptoken);

			ActionLogModel::log('1202', $apptoken, 'remove', $this->user->id, $request->server('REMOTE_ADDR'));

			return response()->json(build_result(["ret" => $ret]));

		} catch (\Exception $e) {
			return response()->json(build_result('', '10001', $e->getMessage()));
		}
	}

	// 创建项目
	public function create(Request $request)
	{
		try{
			$this->validate($request, [
					"template_name" => "required"
				]);
			$template_name = $request -> input("template_name");

			$template_info = TemplateModel::info($template_name);
			if(! $template_info) return response()->json(build_result('', '41001', ''));

			$count = ProjectModel::count($this->user->id);
			$limit = VipModel::getLevelExtraInfoByKey($this->user->id);
			if($count >= $limit) return response()->json(build_result('', '31003', ''));

			$apptoken = generate_nonce_str(8);

			$project = array();
			$project['name'] 	= $template_name;
			$project['title'] 	= empty($template_info->share_title) ? $template_info->title : $template_info->share_title;
			$project['desc'] 	= empty($template_info->share_nofinish_desc) ? $template_info->desc : $template_info->share_nofinish_desc;
			$project['uid'] 	= $this->user->id;
			$project['username'] = $this->user->username;
			$project['token'] 	= $apptoken;
			$project['template_id'] = $template_info->id;
			$project['iscollect'] = $template_info->iscollect;
			$project['setrankbtn'] = $template_info->setrankbtn;
			$project['create_time'] = $this->time;
        	$project['modify_time'] = $this->time;
        	$project['status'] = ProjectModel::STATUS_PUBLISH;
        	$project['icon_url'] = 0;
        	$project['category'] = 0;
        	//$project['extra'] = '';
			$tmp_arr = explode(',', $template_info->raffletypes);
        	$project['raffletype'] = array_shift($tmp_arr);
 			$endtime = strtotime("+14 day"); $project['endtime'] = $endtime;

 			$ret = ProjectModel::create($project);
 			if($ret->id)
 			{
 				$combine_info = build_project_info(array($ret));
 				TemplateModel::where(["id" => $template_info->id])->update(["used_times" => $template_info->used_times + 1]);

 				ActionLogModel::log('1201', $apptoken, 'create', $this->user->id, $request->server('REMOTE_ADDR'));

 				return response()->json(build_result(["info" => $combine_info[0]]));
 			}
 			return response()->json(build_result('', '42001', ''));
		} catch(\Exception $e)
		{
			return response()->json(build_result('', '10001', $e->getMessage()));
		}
	}

	// 复制项目
	// 复制自己的， 拷贝用户案例的
	public function copy(Request $request)
	{
		try
		{
			$this->validate($request, [
					"apptoken" => "required"
				]);
			$apptoken = $request -> input("apptoken");

			$project_info = ProjectModel::info($apptoken);
			if(! $project_info) return response()->json(build_result('', '42002', $apptoken));

			$count = ProjectModel::count($this->user->id);
			$limit = VipModel::getLevelExtraInfoByKey($this->user->id);
			if($count >= $limit) return response()->json(build_result('', '31003', $e->getMessage()));

			$new_token = generate_nonce_str(8);

			$id = $project_info->id;
			unset($project_info->id);

			$tmp_info = json_decode(json_encode($project_info), true);

			$tmp_info['token'] = $new_token;
    		$tmp_info['create_time'] = $this->time;
            $tmp_info['modify_time'] = $this->time;
            $tmp_info['endtime'] = strtotime("+14 day");
    		$tmp_info['status'] =  2;
            $tmp_info['pv'] = "0";
            $tmp_info['uv'] = "0";
            $tmp_info['sc'] = "0";
            $tmp_info['settranscode'] = 0;
            $tmp_info['setwxredpack'] = 0;

            $new_project_info = ProjectModel::create($tmp_info);

            if ( ! $new_project_info->id ) {
            	return response()->json(build_result('', '42001', $e->getMessage()));
            }

            $template_id = $project_info->template_id;
            $template_info = TemplateModel::info_by_id($template_id);
			if(! $template_info) return response()->json(build_result('', '41001', ''));

			// 更新模版的使用次数
			if ( $template_info->id )
			{
				TemplateModel::where(["id" => $template_info->id])->update(["used_times" => $template_info->used_times + 1]);
			}

			//setting 信息 拷贝
			set_sharding_info($id, 1);
			$setting_rows = SettingsModel::where(["appid" => $id, "status" => SettingsModel::STATUS_ACTIVE])->get();
			if ( $setting_rows )
			{
				$insert_rows = array();
				foreach ($setting_rows as $row) {
					if(!in_array($row['item_key'], array('pageview', 'userview', 'sharecount', 'endtime', 'raffletype'))) {
						$insert_rows[] = array(
							'create_time'=> $this->time,
							'modify_time'=> $this->time,
							'appid'      => $new_project_info->id,
							'status'     => 1,
							'item_key'   => $row['item_key'],
							'item_value' => $row['item_value']
							); 
					}
				}
				set_sharding_info($new_project_info->id, 0);
				SettingsModel::create($insert_rows);
			}

			// 拷贝目录
			$project_folder = get_app_dir($apptoken);
			if(is_dir($project_folder)) {
				// return response()->json(build_result('', '42003', $project_folder));
				$new_project_folder = get_app_dir($new_token);
				if(is_dir($new_project_folder) || create_path($new_project_folder)) {
					if(!copy_dir($project_folder, $new_project_folder)){
						return response()->json(build_result('', '20007', $new_project_folder));	
					}
				} else {
					return response()->json(build_result('', '20007', $new_project_folder));
				}
			}
			ActionLogModel::log('1203', $apptoken . '-' . $new_token, 'copy', $this->user->id, $request->server('REMOTE_ADDR'));
 			$combine_info = build_project_info(array($new_project_info));
			return response()->json(build_result(["info" => $combine_info[0]]));
		} catch(\Exception $e)
		{
			return response()->json(build_result('', '10001', $e->getMessage()));
		}
	}

	// 清空数据
	public function clear(Request $request)
	{
		try{
			$this->validate($request, [
				'apptoken' => 'required'
			]);
			$apptoken = $request->input('apptoken');

			$project_info = ProjectModel::info($apptoken);
			if(! $project_info) return response()->json(build_result('', '42002', $apptoken));

			$market_type = $project_info->raffletype;
			switch ($market_type) {
	
				case MarketTypeModel::TYPE_RAFFLE:
				    ClearModel::clear_raffle($project_info->id);
					break;
				case MarketTypeModel::TYPE_RANK:
					ClearModel::clear_rank($project_info->id);
					break;
				case MarketTypeModel::TYPE_ENTRY:
					ClearModel::clear_form($project_info->id);
					break;
				case MarketTypeModel::TYPE_CROWD:
					ClearModel::clear_crowd($project_info->id);
					break;
				case MarketTypeModel::TYPE_CROWD_RAFFLE:
					ClearModel::clear_crowd_raffle($project_info->id);
					break;
				case MarketTypeModel::TYPE_VOTE:
					ClearModel::clear_vote($project_info->id);
					break;
				case MarketTypeModel::TYPE_INDIANA: // 一元夺宝
					// ClearModel::clear_duobao($project_info->id);
					return response()->json(build_result('', '31004', $apptoken));
					break;
				case MarketTypeModel::TYPE_COUPON:
				case MarketTypeModel::TYPE_PPT:
				case MarketTypeModel::TYPE_CARD:
				default:
					break;
			}

			ClearModel::empty_lottery_log($project_info->id);
	        ClearModel::empty_lottery($project_info->id);
	        ClearModel::reset_lottery_prize($project_info->id);

	        //刮菜模版
	        if($project_info->iscollect == 1) {
	            ClearModel::empty_relation_records($project_info->id);
	        }elseif($project_info->iscollect == 2 || $project_info->name == "honghuangyuebing"  || $project_info->name == "shengdanheti") {//洪荒月饼
	            $key = $project_info->name.':'. $project_info->id;
	            ClearModel::empty_collect2($project_info->id, $key);
	        }elseif($project_info->iscollect == 3) {//情侣必须拆
	            ClearModel::empty_collect3($project_info->id);
	        }

	        // 日志
	        ActionLogModel::log('1204', $apptoken, 'clear', $this->user->id, $request->server('REMOTE_ADDR'));
	        return response()->json(build_result(["info" => $project_info]));

		} catch(\Exception $e)
		{
			return response()->json(build_result('', '10001', $e->getMessage()));
		}
	}
}
